package com.victor.pomelo.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * 权限认证授权
 * 
 * @author Victor
 *
 */
@Controller
public class AuthController {

	@RequestMapping(value ={"/",  "/login"}, method = RequestMethod.GET)
	public String login() {
		Subject subject = SecurityUtils.getSubject();
		// 由于可能会不通过logout登出，此处判断是否有Principal存在 如果存在直接跳转到角色选择
		if (subject.getPrincipal() != null && subject.isAuthenticated()) {
			// SecurityUtils.getSubject().logout();
			return "redirect:/manager/main"; // 指定跳转到的操作
		}
		SecurityUtils.getSubject().logout();
		/*
		 * model.addAttribute("isValidateCodeLogin", isValidateCodeLogin(null));
		 * LOGGER.info("Operator init login.jsp");
		 */
		return ("/login");
	}

	@RequestMapping(value = { "/", "login" }, method = RequestMethod.POST)
	public String login(HttpServletRequest request, Model model) {
		String exceptionClassName = (String) request
				.getAttribute("shiroLoginFailure");
		String error = null;
		if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
			error = "用户名/密码错误";
		} else if (IncorrectCredentialsException.class.getName().equals(
				exceptionClassName)) {
			error = "用户名/密码错误";
		} else if (exceptionClassName != null) {
			error = "其他错误：" + exceptionClassName;
		}
		model.addAttribute("error", error);
		return "login";
	}

/*	public String logout(){
		return "login";
	}*/


}
